#!/usr/bin/env python
'''
在neo4j中用如下语句来呈现日课：
MATCH (n) where n.status="on" return n
'''
import os
import argparse
import time
from py2neo import Node,Graph,NodeMatcher,Relationship,RelationshipMatcher
import sxtwl
import collections

Gan = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"]
Zhi = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"]


def getBeamIniMat(rscFilesDir,graph):
    '''
    获取ant目录下的所有天线矩阵
    :param rscFilesDir:
    :return:
    '''
    listFiles = os.listdir(rscFilesDir)
    try:
        for file in listFiles:
            tmpFileName = file.replace(".txt", "").replace(" ", "_").replace('\n', '').replace('\r', '')
            print("处理易理文件：{}".format(tmpFileName))
            with open(os.path.join(rscFilesDir,file)) as file_object:
                for tmp_line in file_object:
                    tmp_line=tmp_line.replace('\n', '').replace('\r', '')
                    if tmp_line.find('合') >= 0:
                        tmp_Node = Node('tmp_line', name=tmp_line)
                        graph.create(tmp_Node)
                        tmp_ab=tmp_line[:tmp_line.find('合')]
                        tmp_len=len(tmp_ab)
                        for i in range(tmp_len):
                            tmp_a=tmp_ab[i]
                            print(tmp_a)
                            tmp_nodes = list(graph.nodes.match(name=tmp_a))
                            print(tmp_nodes)
                            # node found
                            if len(tmp_nodes) > 0:
                                # you have at least 1 node with your property, add relationship
                                # iterate if it's possible that you have more than
                                # one node with your property
                                for tmp_node in tmp_nodes:
                                    # create relationship
                                    graph.create(Relationship(tmp_Node, "包含", tmp_node))
                            else:
                                pass
                    if tmp_line.find('冲') >= 0:
                        tmp_Node = Node('tmp_line', name=tmp_line)
                        tmp_ab = tmp_line[:tmp_line.find('冲')]
                        tmp_a = tmp_ab[0]
                        tmp_b = tmp_ab[1]
                        tmp_nodea = graph.nodes.match(name=tmp_a).first()
                        tmp_nodeb = graph.nodes.match(name=tmp_b).first()
                        graph.create(Relationship(tmp_nodea, "冲", tmp_nodeb))
                        graph.create(Relationship(tmp_nodeb, "冲", tmp_nodea))

                #exit(0)

    except Exception as e:
        print('error:{}!'.format(e))
        exit(1)
    return 0

#--yyyymmddhh 2021040522 --renyyyy 1975
if __name__ == '__main__':
    global tiangan,dizhi,wMonthAdd,nongliyue,nongliri

    time1 = time.time()
    print('Programe starting...')
    graph = Graph("http://localhost:7474",auth=("neo4j", "123"))

    ap = argparse.ArgumentParser()
    ap.add_argument('--yyyymmddhh', required=True)
    ap.add_argument('--renyyyy', required=True)
    args = vars(ap.parse_args())

    numYear = int(args.get('yyyymmddhh')[:4])
    numMon = int(args.get('yyyymmddhh')[4:6])
    numDay = int(args.get('yyyymmddhh')[6:8])
    numHour = int(args.get('yyyymmddhh')[8:10])
    renYear= int(args.get('renyyyy'))
    print("info:{}年{}月{}日{}时 占{}年人".format(numYear, numMon, numDay,numHour,renYear))

    nongligan = (renYear - 1900) % 10 + 6
    nongzhi = (renYear - 1900) % 12
    if (nongligan > 10):
        nongligan = nongligan - 10
    if (nongzhi > 12):
        nongzhi = nongzhi - 12
    ren_gan=Gan[nongligan]
    ren_zhi=Zhi[nongzhi]

    # 从公历年月日获取一天的信息
    day = sxtwl.fromSolar(numYear, numMon, numDay)

    yTG = day.getYearGZ()
    print("年干支", Gan[yTG.tg] + Zhi[yTG.dz])
    year_gan = Gan[yTG.tg]
    year_zhi = Zhi[yTG.dz]

    # 月干支
    mTG = day.getMonthGZ()
    print("月干支", Gan[mTG.tg] + Zhi[mTG.dz])
    mon_gan=Gan[mTG.tg]
    mon_zhi=Zhi[mTG.dz]

    # 日干支
    dTG = day.getDayGZ()
    print("日干支", Gan[dTG.tg] + Zhi[dTG.dz])
    day_gan = Gan[dTG.tg]
    day_zhi = Zhi[dTG.dz]

    # 时干支,传24小时制的时间，分早晚子时
    hour = numHour
    sTG = day.getHourGZ(hour)
    print("%d时的干支" % (hour,), Gan[sTG.tg] + Zhi[sTG.dz])
    hour_gan=Gan[sTG.tg]
    hour_zhi =Zhi[sTG.dz]

    print("info:{}{}年{}{}月{}{}日{}{}时 占{}{}年人".format(year_gan, year_zhi, mon_gan,mon_zhi, day_gan,day_zhi,hour_gan,hour_zhi,ren_gan,ren_zhi))

    rikeList=[year_gan,year_zhi,mon_gan,mon_zhi, day_gan,day_zhi,hour_gan,hour_zhi,ren_gan,ren_zhi]

    matcher = NodeMatcher(graph)
    relmatcher= RelationshipMatcher(graph)

    tmpgan_nodes= matcher.match("干")
    for tmp_node in tmpgan_nodes:
        tmp_key=dict(tmp_node)
        #print(tmp_key)
        #print(tmp_key['status'])
        if tmp_key['name'] in rikeList:
            tmp_node.update({'status': 'on'})  # 使用update方法，而不是用setdefault()
            graph.push(tmp_node)  ##push()方法将更新后的节点压入图中
            rels = relmatcher.match((None, tmp_node), r_type="包含")
            for rel in rels:
                rel.update({'status': 'on'})  # 使用update方法，而不是用setdefault()
                graph.push(rel)  ##push()方法将更新后的节点压入图中
        else:
            tmp_node.update({'status': 'off'})  # 使用update方法，而不是用setdefault()
            graph.push(tmp_node)  ##push()方法将更新后的节点压入图中
            rels = relmatcher.match((None, tmp_node), r_type="包含")
            for rel in rels:
                rel.update({'status': 'off'})  # 使用update方法，而不是用setdefault()
                graph.push(rel)  ##push()方法将更新后的节点压入图中

    tmpzhi_nodes = matcher.match("支")
    for tmp_node in tmpzhi_nodes:
        tmp_key = dict(tmp_node)
        #print(tmp_key)
        # print(tmp_key['status'])
        if tmp_key['name'] in rikeList:
            tmp_node.update({'status': 'on'})  # 使用update方法，而不是用setdefault()
            graph.push(tmp_node)  ##push()方法将更新后的节点压入图中
            rels = relmatcher.match((None, tmp_node), r_type="包含")
            for rel in rels:
                rel.update({'status': 'on'})  # 使用update方法，而不是用setdefault()
                graph.push(rel)  ##push()方法将更新后的节点压入图中
        else:
            tmp_node.update({'status': 'off'})  # 使用update方法，而不是用setdefault()
            graph.push(tmp_node)  ##push()方法将更新后的节点压入图中
            rels = relmatcher.match((None, tmp_node), r_type="包含")
            for rel in rels:
                rel.update({'status': 'off'})  # 使用update方法，而不是用setdefault()
                graph.push(rel)  ##push()方法将更新后的节点压入图中

    #局对干支的比生克关系建立
    tmpju_nodes = matcher.match("局")
    for tmp_node in tmpju_nodes:
        tmp_key = dict(tmp_node)
        rels = relmatcher.match((tmp_node,None),r_type="包含")
        rels_size=rels.count()
        tmp_sum=0
        for rel in rels:
            rel_key = dict(rel)
            if rel_key['status']=='on':
                tmp_sum=tmp_sum+1

        if tmp_sum>rels_size/2:
            tmp_node.update({'status': 'on'})  # 使用update方法，而不是用setdefault()
            graph.push(tmp_node)  ##push()方法将更新后的节点压入图中
        else:
            tmp_node.update({'status': 'off'})  # 使用update方法，而不是用setdefault()
            graph.push(tmp_node)  ##push()方法将更新后的节点压入图中

    # 打印用时
    time2 = time.time()
    print('total used {0} min.'.format(round((time2 - time1) / 60, 2)))
